import React, { useEffect } from 'react';
import { Table, DatePicker, Space, Select, Button, Tag, Card } from 'antd';
import { SearchOutlined, DownloadOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import zhCN from 'antd/es/locale/zh_CN'; // 引入中文语言包
import { ConfigProvider } from 'antd'; // 引入 ConfigProvider
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '../../store';
import { setLogs, setLoading, Log } from '../../store/slices/logSlice';
import { getLogs,exportLogs} from '../../api/log';

// 确保 dayjs 的默认语言被设置为中文
dayjs.locale('zh-cn');

interface Filters {
  dateRange: [Dayjs, Dayjs] | null;
  type: string | null;
  user: string | null;
}

const LogList: React.FC = () => {
  const dispatch = useDispatch();
  const { logs, loading } = useSelector((state: RootState) => state.log);
  const [filters, setFilters] = React.useState<Filters>({
    dateRange: null,
    type: null,
    user: null,
  });
  // 新增：存储原始日志数据
  const [originalLogs, setOriginalLogs] = React.useState<Log[]>([]);

  useEffect(() => {
    const fetchLogs = async () => {
      dispatch(setLoading(true));
      try {
        // 调用 getLogs 方法获取日志数据
        const { logs } = await getLogs();
        dispatch(setLogs(logs));
        // 存储原始日志数据
        setOriginalLogs(logs);
      } catch (error) {
        console.error('Failed to fetch logs:', error);
      } finally {
        dispatch(setLoading(false));
      }
    };

    fetchLogs();
  }, [dispatch]);

  const columns: ColumnsType<Log> = [
    {
      title: '用户',
      dataIndex: 'user',
      key: 'user',
      width: 120,
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => (
        <Tag color={
          type === 'create' ? 'success' :
          type === 'update' ? 'processing' :
          type === 'delete' ? 'error' :
          'default'
        }>
          {type.toUpperCase()}
        </Tag>
      ),
    },
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: 180,
      render: (timestamp: string) => dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss'), // 修改日期格式为 YYYY-MM-DD HH:mm:ss
    },
    {
      title: '详情',
      dataIndex: 'details',
      key: 'details',
      ellipsis: true,
    },
  ];

  const handleDateRangeChange = (dates: [Dayjs, Dayjs] | null) => {
    setFilters(prev => ({
      ...prev,
      dateRange: dates
    }));
  };

  const handleSearch = () => {
    const { dateRange, type, user } = filters;
    if (!dateRange && !type && !user) {
      // 如果所有筛选条件都为空，直接显示所有原始数据
      dispatch(setLogs(originalLogs));
      return;
    }

    // 根据筛选条件过滤日志数据
    const filteredLogs = originalLogs.filter(log => {
      // 日期范围过滤
      if (dateRange) {
        const logDate = dayjs(log.timestamp);
        if (logDate.isBefore(dateRange[0]) || logDate.isAfter(dateRange[1])) {
          return false;
        }
      }

      // 类型过滤
      if (type && log.type !== type) {
        return false;
      }

      // 用户过滤
      if (user && log.user !== user) {
        return false;
      }

      return true;
    });

    // 更新 Redux 中的日志数据
    dispatch(setLogs(filteredLogs));
  };

  const handleExport = async () => {
    try {
      // 直接调用 exportLogs 接口获取文件流
      const blob = await exportLogs();

      // 创建临时的 Blob URL
      const url = URL.createObjectURL(blob);

      // 创建隐藏的 <a> 标签并触发下载
      const a = document.createElement('a');
      a.href = url;
      a.download = 'logs_export.xlsx'; // 设置下载文件名
      document.body.appendChild(a);
      a.click();

      // 释放 URL 对象
      URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      console.error('Failed to export logs:', error);
    }
  };

  const userOptions = [...new Set(logs.map(log => log.user))].map(user => ({
    label: user,
    value: user,
  }));

  const typeOptions = [
    { label: '创建', value: 'create' },
    { label: '更新', value: 'update' },
    { label: '删除', value: 'delete' },
    { label: '登录', value: 'login' },
  ];

  return (
    <ConfigProvider locale={zhCN}> {/* 使用 ConfigProvider 包裹组件并设置语言环境 */}
      <div style={{ padding: '24px', background: '#f0f2f5', minHeight: '100vh' }}>
        <div style={{ maxWidth: '1200px', margin: '0 auto' }}>
          <Card
            title="日志管理"
            bordered={false}
            style={{ marginBottom: 24 }}
          >
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              {/* 筛选区域 - 响应式布局 */}
              <div style={{
                display: 'flex',
                flexWrap: 'wrap',
                gap: '16px',
                marginBottom: '16px'
              }}>
                {/* 日期选择器 - 在小屏幕上占满宽度 */}
                <div style={{
                  flex: '1 1 300px',
                  minWidth: '280px'
                }}>
                  <span style={{ marginRight: '8px' }}>日期:</span>
                  <DatePicker.RangePicker
                    onChange={(dates) => handleDateRangeChange(dates as [Dayjs, Dayjs] | null)}
                    style={{ width: 'calc(100% - 80px)' }}
                  />

                </div>

                {/* 类型和用户选择器 - 在小屏幕上占半宽 */}
                <div style={{
                  flex: '1 1 200px',
                  minWidth: '150px',
                  display: 'flex',
                  alignItems: 'center'
                }}>
                  <span style={{ marginRight: '8px' }}>类型:</span>
                  <Select
                    style={{ flex: 1 }}
                    allowClear
                    placeholder="选择类型"
                    options={typeOptions}
                    onChange={(value) => setFilters(prev => ({ ...prev, type: value }))}
                  />
                </div>

                <div style={{
                  flex: '1 1 200px',
                  minWidth: '150px',
                  display: 'flex',
                  alignItems: 'center'
                }}>
                  <span style={{ marginRight: '8px' }}>用户:</span>
                  <Select
                    style={{ flex: 1 }}
                    allowClear
                    placeholder="选择用户"
                    options={userOptions}
                    onChange={(value) => setFilters(prev => ({ ...prev, user: value }))}
                  />
                </div>

                {/* 按钮组 - 在小屏幕上占满宽度 */}
                <div style={{
                  flex: '1 1 200px',
                  minWidth: '200px',
                  display: 'flex',
                  justifyContent: 'flex-end',
                  gap: '8px'
                }}>
                  <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                    搜索
                  </Button>
                  <Button icon={<DownloadOutlined />} onClick={handleExport}>
                    导出日志
                  </Button>
                </div>
              </div>

              {/* 表格区域 */}
              <Table
                columns={columns}
                dataSource={logs}
                rowKey="id"
                loading={loading}
                pagination={{
                  total: logs.length,
                  pageSize: 10,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total) => `共 ${total} 条记录`,
                  responsive: true
                }}
                scroll={{ x: 'max-content' }}
                style={{ overflowX: 'auto' }}
              />
            </Space>
          </Card>
        </div>
      </div>
    </ConfigProvider>
  );
};

export default LogList;
